package com.far.util;

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


public class Q {
	
	
	public static byte[] toByteArray(String filename) throws IOException {

		System.out.println("filename:" + filename);
		File f = new File(filename);
		if (!f.exists()) {
			throw new FileNotFoundException(filename);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	

    /**
     * 文件转
     * @param fileUrl
     * @return
     */
    public static byte[] fileUrl2Byte(String fileUrl) {
        File file = new File(fileUrl);
        try {
            InputStream inStream = new FileInputStream(file);
            int length = (int)file.length();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[length];
            int len = -1;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.flush();
            outStream.close();
            inStream.close();
            return outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	
	
	public static String  getUUid() {
		 String uuid = UUID.randomUUID().toString()+"$$";//.replaceAll("-","");
       return uuid;
	}

	public static String uploadir() {
		return "uploadFiles";
	}
	
	
	 public static String GetFileSize(File file){
		    String size = ""; 
		    if(file.exists() && file.isFile()){
		    long fileS = file.length();
		     DecimalFormat df = new DecimalFormat("#.00"); 
		          if (fileS < 1024) {
		             size = df.format((double) fileS) + "BT";
		          } else if (fileS < 1048576) {
		             size = df.format((double) fileS / 1024) + "KB";
		          } else if (fileS < 1073741824) {
		             size = df.format((double) fileS / 1048576) + "MB";
		          } else {
		             size = df.format((double) fileS / 1073741824) +"GB";
		          }
		    }else if(file.exists() && file.isDirectory()){
		    size = "";
		    }else{
		    size = "0BT";
		    }
		    return size;
		   }
	 
	 public static String GetFileSize(long length ){
		    String size = "";  
		    long fileS = length;
		     DecimalFormat df = new DecimalFormat("#.00"); 
		          if (fileS < 1024) {
		             size = df.format((double) fileS) + "BT";
		          } else if (fileS < 1048576) {
		             size = df.format((double) fileS / 1024) + "KB";
		          } else if (fileS < 1073741824) {
		             size = df.format((double) fileS / 1048576) + "MB";
		          } else {
		             size = df.format((double) fileS / 1073741824) +"GB";
		          }
		    
		    return size;
		   }
	 

	/**
	 * 判读是否为空
	 *
	 * @param str
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		}
		if (obj instanceof CharSequence) {
			return ((CharSequence) obj).length() == 0;
		}
		if (obj instanceof Collection) {
			return ((Collection) obj).isEmpty();
		}
		if (obj instanceof Map) {
			return ((Map) obj).isEmpty();
		}
		if (obj instanceof Object[]) {
			Object[] object = (Object[]) obj;
			if (object.length == 0) {
				return true;
			}
			boolean empty = true;
			for (int i = 0; i < object.length; i++) {
				if (!isEmpty(object[i])) {
					empty = false;
					break;
				}
			}
			return empty;
		}
		return false;
	}

	/**
	 * 判读是否为空，为空取默认值
	 *
	 * @param str
	 * @return
	 * @return
	 * @return
	 */
	public static <T> T isEmpty(T obj, T defaultValue) {
		if (isEmpty(obj)) {
			return defaultValue;
		}
		return obj;
	}

	/**
	 * 判断某个字符串是否存在于数组中
	 *
	 * @param stringArray
	 *            原数组
	 * @param source
	 *            查找的字符串
	 * @return 是否找到
	 */
	public static boolean contains(String[] stringArray, String source) {
		// 转换为list
		List<String> tempList = Arrays.asList(stringArray);
		// 利用list的包含方法,进行判断
		if (tempList.contains(source)) {
			return true;
		} else {
			return false;
		}
	}

	public static long now() {
		return (long) (new Date().getTime() / 1000L);
	}



	/**
	 * 获取UUID
	 * 
	 * @return
	 */
	public static String getUuid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}

	/**
	 * 往数组里面添加数组
	 * 
	 * @param array
	 * @param objects
	 * @return
	 */
	public static Object[] addObjectToArray(Object[] array, Object... objects) {
		if (array == null) {
			return objects;
		}
		if (objects == null) {
			return array;
		}
		Object[] newArr = new Object[array.length + objects.length];
		System.arraycopy(array, 0, newArr, 0, array.length);
		int i = newArr.length - objects.length;
		for (int j = 0; i < newArr.length; ++j) {
			newArr[i] = objects[j];
			++i;
		}
		return newArr;
	}

	/**
	 * 创建指定数量的随机字符串
	 *
	 * @param numberFlag
	 *            是否是数字
	 * @param length
	 * @return
	 */
	public static String getRandom(boolean numberFlag, int length) {
		String retStr = "";
		String strTable = numberFlag ? "1234567890"
				: "1234567890abcdefghijkmnpqrstuvwxyz";
		int len = strTable.length();
		boolean bDone = true;
		do {
			retStr = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = strTable.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				retStr += strTable.charAt(intR);
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);
		return retStr;
	}

	/**
	 * 获取两个数之间的随机
	 * 
	 * @param x
	 * @param y
	 */
	public static int getRandomNumInTwoIntNum(int x, int y) {
		Random random = new Random();
		int cha = Math.abs(x - y);
		if (cha <= 1) {
			System.out.println("两个数字之间没有整数了!");
		} else {
			int randomCha = random.nextInt(cha) + 1;
			if (randomCha >= cha) {
				randomCha = cha - 1;
			}
			if (x > y) {
				return (randomCha + y);
			}
			if (x < y) {
				return (randomCha + x);
			}
		}
		return -1;
	}

	// 创建目录
	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {// 判断目录是否存在
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
			destDirName = destDirName + File.separator;
		}
		if (dir.mkdirs()) {// 创建目标目录
			System.out.println("创建目录成功！" + destDirName);
			return true;
		} else {
			System.out.println("创建目录失败！");
			return false;
		}
	}

	/**
	 * 处理中文URL
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String makeUrl(String url) throws Exception {
		String str = url;
		str = str.replace("/", "R870830R").replace(":", "F870830F");
		String path = URLEncoder.encode(str, "UTF8");
		path = path.replace("R870830R", "/").replace("F870830F", ":")
				.replace("+", "%20");
		return path;
	}

	/**
	 * RESPONSE MESSAGE
	 * 
	 * @param response
	 */
	public static void render(HttpServletResponse response, String text,
			String encoding, String contentType) throws Exception {
		response.setContentType(contentType);
		response.setCharacterEncoding(encoding);
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
		ServletOutputStream out = response.getOutputStream();
		out.write(text.getBytes(encoding));
		out.flush();
	}

	public static void render(HttpServletResponse response, String message) {
		try {
			render(response, message, "UTF-8", "application/json");
		} catch (Exception e) {
		}
	}

	public static Map<String, Integer> listToMap(List<Map<String, Object>> data) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (Map<String, Object> obj : data) {
			String name = (String) obj.get("name");
			Integer id = (Integer) obj.get("id");
			map.put(name, id);
		}
		return map;
	}

	/**
	 * 获取当前小时 时间的时间戳
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static long getCurrentHourTime() throws ParseException {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
		String dateString = df.format(new Date());
		long time2 = df.parse(dateString).getTime() / 1000L;
		return time2;
	}

	/**
	 * 把long 转换成 日期 再转换成String类型
	 */
	public static String transferLongToDate(String dateFormat, Long millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = new Date(millSec * 1000L);
		return sdf.format(date);
	}

	/**
	 * 获取昨天的时间
	 * 
	 * @param dateFormat
	 * @return
	 */
	public static String getYestDate(String dateFormat) {

		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		Date time = cal.getTime();
		return sdf.format(time);
	}
	
	/**
	 * 计算两个时间戳直接的距离（可年）
	 * 
	 * @param dateFormat
	 * @return
	 */
	public static int CalculateTime(Long startTime, Long endTime) {
		if (startTime > endTime) {
			return -1;
		}
		Long s = (endTime - startTime) / ( 60 * 60 * 24 * 365);
		return s.intValue();
	}

	/***
	 * 通过图片二进制流判断文件的类型（后缀）
	 * 
	 * @param src
	 * @return
	 */

	public static String getTypeByInputStream(InputStream is) {

		byte[] src = new byte[3];
		try {
			is.read(src, 0, src.length);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		String checkedStr = stringBuilder.toString().toUpperCase();
		/**
		 * 常用文件的文件头如下：(以前六位为准) JPEG (jpg)，文件头：FFD8FF PNG (png)，文件头：89504E47 GIF
		 * (gif)，文件头：47494638 TIFF (tif)，文件头：49492A00 Windows Bitmap
		 * (bmp)，文件头：424D CAD (dwg)，文件头：41433130 Adobe Photoshop
		 * (psd)，文件头：38425053 Rich Text Format (rtf)，文件头：7B5C727466 XML
		 * (xml)，文件头：3C3F786D6C HTML (html)，文件头：68746D6C3E Email [thorough only]
		 * (eml)，文件头：44656C69766572792D646174653A Outlook Express
		 * (dbx)，文件头：CFAD12FEC5FD746F Outlook (pst)，文件头：2142444E MS Word/Excel
		 * (xls.or.doc)，文件头：D0CF11E0 MS Access (mdb)，文件头：5374616E64617264204A
		 * WordPerfect (wpd)，文件头：FF575043 Postscript
		 * (eps.or.ps)，文件头：252150532D41646F6265 Adobe Acrobat
		 * (pdf)，文件头：255044462D312E Quicken (qdf)，文件头：AC9EBD8F Windows Password
		 * (pwl)，文件头：E3828596 ZIP Archive (zip)，文件头：504B0304 RAR Archive
		 * (rar)，文件头：52617221 Wave (wav)，文件头：57415645 AVI (avi)，文件头：41564920
		 * Real Audio (ram)，文件头：2E7261FD Real Media (rm)，文件头：2E524D46 MPEG
		 * (mpg)，文件头：000001BA MPEG (mpg)，文件头：000001B3 Quicktime
		 * (mov)，文件头：6D6F6F76 Windows Media (asf)，文件头：3026B2758E66CF11 MIDI
		 * (mid)，文件头：4D546864
		 */
		switch (checkedStr) {
		case "FFD8FF":
			return "jpg";
		case "89504E":
			return "png";
		case "474946":
			return "jif";

		default:
			return "0000";
		}
	}

	/**
	 * 对double数的四舍五入操作
	 * 
	 * @param f
	 * @param num保留位数
	 * @return
	 */
	public static double halfAdjust(double f, int num) {
		BigDecimal b = new BigDecimal(f);
		double f1 = b.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f1;
	}

	/**
	 * 将指定日期格式的时间转换为时间戳
	 * 
	 * @param DateStr
	 *            DateFormat
	 * @param long
	 * @return
	 */
	public static long getLongByDateFormat(String DateStr, String DateFormat) {
		SimpleDateFormat sdf = new SimpleDateFormat(DateFormat);
		Date date = null;
		try {
			date = sdf.parse(DateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date.getTime() / 1000L;
	}
	
	public static boolean isImage(InputStream inputStream) {
        if (inputStream == null) {
            return false;
        }
        Image img;
        try {
            img = ImageIO.read(inputStream);
            return !(img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0);
        } catch (Exception e) {
            return false;
        }
    }

	/**
	 * 生成n位随机数
	 * @return
	 */
	public static String getLongRand(Integer length) {
		String val = "";
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			val += String.valueOf(random.nextInt(10));
		}
		return val;
	}
	

	/**
	 * 判断是否为正整数（用于排序字段非必填）
	 * @return
	 */
	public static boolean isNumeric(String string){
	    Pattern pattern = Pattern.compile("[0-9]*");
	    return pattern.matcher(string).matches();   
	}

	
	/**
	 * 获取上传文件的新命名
	 * @return
	 */
	public static String getUploadFlieNames(InputStream in, String filename) {
		Image img = null;
		String ext = filename.substring(filename.lastIndexOf("."));
		try {
			//图片类型
            img = ImageIO.read(in);
            int w = img.getWidth(null);   
    		int h = img.getHeight(null); 
            if(img == null || w <= 0 || h <= 0 || h > 2500){
            	throw new Exception();
            }
            return Q.getUuid() + "_" + w + "_" + h + ext;
        } catch (Exception e) {
        	//其它类型
            return Q.getUuid() + ext;
        }
	}
	
	
	
	//判断两个字符串是否有重复数字
	
	public static boolean containRepeatChar(String str,String str1){
        try {
            String[] arr1 = str.split(",");
            String[] arr2 = str1.split(",");
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < arr2.length; i++) {
                for (int j = 0; j < arr1.length; j++) {
                    if (arr1[j].equals(arr2[i])) {
                        sb.append(arr1[j] + ",");
                    }
                }
            }
            System.out.println("结果：" + sb.toString().substring(0, sb.toString().length() - 1));
            return true;
        }catch (Exception e){
            System.out.println("结果:没有重复的数据");
            return false;
        }
    }


}
